package com.itheima.bos.web.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.itheima.bos.domain.constant.Constant;
import com.itheima.bos.domain.page.PageBean;
import com.itheima.bos.domain.take_delivery.Promotion;
import com.itheima.bos.web.common.BaseAction;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@SuppressWarnings("all")
public class PromotionAction extends BaseAction<Promotion> {

	// 前端分页查询
	@Action(value = "promotion_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		// 调用webService,从bos中查询宣传任务数据
		PageBean<Promotion> pageBean = WebClient
				.create(Constant.BOS_MANAGEMENT_URL
						+ "/services/promotionService/pageQuery?page=" + page
						+ "&rows=" + rows).accept(MediaType.APPLICATION_JSON)
				.get(PageBean.class);
		pushPageDataToValueStack(pageBean);
		return SUCCESS;
	}

	// 静态页面展示
	@Action(value = "promotion_showDetail")
	public String showDetail() throws IOException, TemplateException {
		// 获取路径
		String htmlPath = ServletActionContext.getServletContext().getRealPath(
				"/freemarker");
		File htmlFile = new File(htmlPath + "/" + model.getId() + ".html");

		// 判断文件是否存在
		if (!htmlFile.exists()) {
			// 文件不存在,使用模板生成界面
			Configuration configuration = new Configuration(
					Configuration.VERSION_2_3_22);
			configuration.setDirectoryForTemplateLoading(new File(
					ServletActionContext.getServletContext().getRealPath(
							"/WEB-INF/freemarker_templates")));
			// 获取模板对象
			Template template = configuration
					.getTemplate("promotion_detail.ftl");
			// 动态数据
			Promotion promotion = WebClient
					.create(Constant.BOS_MANAGEMENT_URL
							+ "/services/promotionService/promotion/"
							+ model.getId()).accept(MediaType.APPLICATION_JSON)
					.get(Promotion.class);
			Map<String, Object> parametMap = new HashMap<String, Object>();
			parametMap.put("promotion", promotion);
			// 合并输出
			template.process(parametMap, new OutputStreamWriter(
					new FileOutputStream(htmlFile), "utf-8"));
		}
		// 文件存在，直接将页面返回
		ServletActionContext.getResponse().setContentType(
				"text/html;charset=utf-8");
		FileUtils.copyFile(htmlFile, ServletActionContext.getResponse()
				.getOutputStream());
		return NONE;
	}
}
